﻿using System;
using System.Text;
using System.Security.Cryptography;

public class hash
{
    private hash() { }

    //---------------------------------------------------------------------------
    public static string get_hex_string(byte[] bytes)
    {
        string res = "";

        foreach (byte b in bytes)
            res += String.Format("{0:x2}", b);

        return res;
    }
    //---------------------------------------------------------------------------
    public static string sha1(string str, Encoding enc, bool hash_terminating_null)
    {
        if (!hash_terminating_null)
        {
            return sha1(enc.GetBytes(str));
        }
        else
        {
            byte[] res = null;
            if (enc == Encoding.ASCII || enc == Encoding.UTF8)
            {
                res = new byte[str.Length + 1];
            }
            else if (enc == Encoding.Unicode)
            {
                res = new byte[(str.Length + 1) * 2];
            }
            else // default
            {
                res = new byte[(str.Length + 1) * 2];
            }
            
            byte[] temp = enc.GetBytes(str);
            Array.Copy(temp, res, temp.Length);

            return sha1(res);
        }
    }
    //---------------------------------------------------------------------------
    public static string sha1(byte[] bytes)
    {
        SHA1 sha1 = SHA1.Create();
        byte[] bHash = sha1.ComputeHash(bytes);
        return get_hex_string(bHash);
    }
    //---------------------------------------------------------------------------
}